﻿using RuiXinCoffee.BLL;
using RuiXinCoffee.Model;
using RuiXinCoffee.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RuiXinCoffee.UI
{
    public partial class AdminProductForm : BaseForm
    {
        private int? editingProductId = null;
        private string selectedImagePath = null;
        private Image tempImage = null; //临时存储选择的图片
        private string _originalImageUrl = null; // 用于存储原始图片路径

        public AdminProductForm()
        {
            InitializeComponent();
            InitCategory();
            pictureBoxProduct.Paint += pictureBoxProduct_Paint;
            pictureBoxProduct.Image = null; //确保初始无图片
        }

        public AdminProductForm(int productId) : this()
        {
            try
            {
                editingProductId = productId;
                LoadProductForEdit(productId);
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        private void InitCategory()
        {
            comboBoxCategory.Items.AddRange(new string[] { "美式", "拿铁", "其他" });
            comboBoxCategory.SelectedIndex = 0;
        }

        private void buttonAddnew_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(textBoxProductName.Text))
                {
                    throw new UserOperationException("请输入商品名称");
                }
                if (comboBoxCategory.SelectedIndex < 0)
                {
                    throw new UserOperationException("请选择商品类别");
                }
                if (string.IsNullOrWhiteSpace(textBoxPrice.Text) || !decimal.TryParse(textBoxPrice.Text, out decimal price))
                {
                    throw new UserOperationException("请输入正确的价格");
                }
                if (pictureBoxProduct.Image == null)
                {
                    throw new UserOperationException("请添加商品图片");
                }

                string imageUrl = null;
                bool isNewImageSelected = tempImage != null || (!string.IsNullOrEmpty(selectedImagePath) && !selectedImagePath.Contains(AppDomain.CurrentDomain.BaseDirectory));

                // 判断是否是编辑模式且没有选择新图片
                if (editingProductId.HasValue && !isNewImageSelected)
                {
                    // 编辑模式下未选择新图片，保留原图片路径
                    var productService = new ProductService();
                    var originalProduct = productService.GetProductById(editingProductId.Value);
                    if (originalProduct != null)
                    {
                        imageUrl = originalProduct.ImageUrl;
                    }
                }
                else
                {
                    // 新增模式或编辑模式下选择了新图片
                    if (tempImage != null)
                    {
                        string tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".jpg");

                        try
                        {
                            string tempDir = Path.GetDirectoryName(tempFile);
                            if (!Directory.Exists(tempDir))
                            {
                                Directory.CreateDirectory(tempDir);
                            }

                            //保存临时图片
                            using (var ms = new MemoryStream())
                            {
                                //先保存到内存流
                                tempImage.Save(ms, ImageFormat.Jpeg);
                                ms.Position = 0;

                                //再从内存流写入文件
                                using (var fs = new FileStream(tempFile, FileMode.Create, FileAccess.Write))
                                {
                                    byte[] buffer = ms.ToArray();
                                    fs.Write(buffer, 0, buffer.Length);
                                    fs.Flush();
                                }
                            }

                            imageUrl = ImageHelper.SaveImage(tempFile);

                            try { File.Delete(tempFile); } catch {}
                        }
                        catch (Exception ex)
                        {
                            throw new ImageProcessException("处理图片时出错", ex);
                        }
                    }
                    else if (!string.IsNullOrEmpty(selectedImagePath) && File.Exists(selectedImagePath))
                    {
                        //如果有原始路径且文件存在，尝试使用原始路径
                        imageUrl = ImageHelper.SaveImage(selectedImagePath);
                    }
                    else
                    {
                        throw new UserOperationException("无法处理所选图片，请重新选择");
                    }
                }

                var product = new Product
                {
                    Name = textBoxProductName.Text.Trim(),
                    Price = price,
                    Description = textBoxDescription.Text.Trim(),
                    ImageUrl = imageUrl,  //使用相对路径，可能是原来的或新的
                    CategoryId = comboBoxCategory.SelectedIndex + 1,
                    IsOnSale = true
                };

                var service = new ProductService();
                bool result;
                if (editingProductId.HasValue)
                {
                    product.Id = editingProductId.Value;
                    result = service.UpdateProduct(product);
                }
                else
                {
                    result = service.AddProduct(product);
                }

                if (result)
                {
                    MessageBox.Show("商品操作成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.DialogResult = DialogResult.OK;
                }
                else
                {
                    throw new BusinessException("商品操作失败，请稍后重试");
                }
            }
            catch (RuiXinException ex)
            {
                HandleException(ex);
            }
            catch (Exception ex)
            {
                HandleException(new BusinessException("操作失败", ex));
            }
        }

        private void pictureBoxProduct_Paint(object sender, PaintEventArgs e)
        {
            if (pictureBoxProduct.Image == null)
            {
                string text = "请添加商品图片";
                using (Font font = new Font("微软雅黑", 12, FontStyle.Regular))
                using (Brush brush = new SolidBrush(Color.Gray))
                {
                    SizeF textSize = e.Graphics.MeasureString(text, font);
                    float x = (pictureBoxProduct.Width - textSize.Width) / 2;
                    float y = (pictureBoxProduct.Height - textSize.Height) / 2;
                    e.Graphics.DrawString(text, font, brush, x, y);
                }
            }
        }

        private void buttonSelectImage_Click(object sender, EventArgs e)
        {
            try
            {
                using (OpenFileDialog dlg = new OpenFileDialog())
                {
                    dlg.Title = "选择商品图片";
                    dlg.Filter = "图片文件|*.jpg;*.jpeg;*.png;*.bmp;*.gif";
                    if (dlg.ShowDialog() == DialogResult.OK)
                    {
                        try
                        {
                            //记录选择的图片完整路径
                            selectedImagePath = dlg.FileName;

                            //检查文件是否存在
                            if (!File.Exists(selectedImagePath))
                            {
                                throw new FileNotFoundException($"找不到文件: {selectedImagePath}");
                            }

                            //使用更安全的方式加载图片
                            using (var memoryStream = new MemoryStream())
                            {
                                //首先将文件读入内存流
                                using (var fileStream = new FileStream(selectedImagePath, FileMode.Open, FileAccess.Read))
                                {
                                    byte[] buffer = new byte[1024];
                                    int bytesRead;
                                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        memoryStream.Write(buffer, 0, bytesRead);
                                    }
                                    memoryStream.Position = 0;
                                }

                                using (var originalImage = Image.FromStream(memoryStream))
                                {
                                    var bmp = new Bitmap(pictureBoxProduct.Width, pictureBoxProduct.Height);
                                    using (var g = Graphics.FromImage(bmp))
                                    {
                                        g.Clear(Color.White);
                                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                                        var rect = ImageHelper.GetScaledRectangle(originalImage.Size, pictureBoxProduct.Size);
                                        g.DrawImage(originalImage, rect);
                                    }

                                    if (pictureBoxProduct.Image != null)
                                    {
                                        pictureBoxProduct.Image.Dispose();
                                    }

                                    if (tempImage != null)
                                    {
                                        tempImage.Dispose();
                                    }

                                    tempImage = new Bitmap(originalImage);

                                    pictureBoxProduct.Image = bmp;
                                }
                            }
                        }
                        catch (OutOfMemoryException)
                        {
                            throw new ImageProcessException("无法加载图片：图片格式不受支持或文件已损坏");
                        }
                        catch (Exception ex)
                        {
                            throw new ImageProcessException("无法加载预览图片", ex);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException(new ImageProcessException("选择图片时发生错误", ex));
            }
        }

        private void LoadProductForEdit(int productId)
        {
            try
            {
                var service = new ProductService();
                var product = service.GetProductById(productId);
                if (product != null)
                {
                    textBoxProductName.Text = product.Name;
                    textBoxPrice.Text = product.Price.ToString();
                    textBoxDescription.Text = product.Description;
                    comboBoxCategory.SelectedIndex = product.CategoryId - 1;
                    _originalImageUrl = product.ImageUrl; // 保存原始图片路径

                    if (!string.IsNullOrEmpty(product.ImageUrl))
                    {
                        try
                        {
                            //使用ImageHelper加载
                            Image loadedImage = ImageHelper.LoadImage(product.ImageUrl);

                            if (tempImage != null)
                            {
                                tempImage.Dispose();
                            }
                            tempImage = null; // 将tempImage设为null，表示没有选择新图片

                            pictureBoxProduct.Image = loadedImage;

                            // 设置selectedImagePath为相对于程序的路径，而不是外部路径
                            selectedImagePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, product.ImageUrl);
                        }
                        catch (Exception ex)
                        {
                            throw new ImageProcessException("加载产品图片失败", ex);
                        }
                    }
                }
                else
                {
                    throw new BusinessException($"找不到ID为{productId}的商品");
                }
            }
            catch (RuiXinException ex)
            {
                HandleException(ex);
            }
            catch (Exception ex)
            {
                HandleException(new BusinessException("加载商品信息失败", ex));
            }
        }
    }
}
